/**
 * @Title: ExcelServiceImpl.java
 * @Package com.lemon.controller.excel
 * @Description: (一句话阐述):
 * @author Ran_cc
 * @date 2018年8月10日
 * @version V1.0
 */
package com.lemon.controller.excel;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.lemon.conf.content.IdTypeHandler;
import com.lemon.mapper.cityRun.CrShopGoodsMapper;
import com.lemon.mapper.cityRun.CrShopGoodsSpecMapper;
import com.lemon.mapper.cityRun.CrShopGoodsTypeMapper;
import com.lemon.mapper.cityRun.crShopPicMapper;
import com.lemon.mapper.cityRun.crShopPicTypeMapper;
import com.lemon.model.cityRun.CrShopGoods;
import com.lemon.model.cityRun.CrShopGoodsSpec;
import com.lemon.model.cityRun.CrShopGoodsType;
import com.lemon.model.cityRun.crShopPic;
import com.lemon.model.cityRun.crShopPicType;
import com.lemon.utils.StringUtil;

/**
 * <p>
 * Title: ExcelServiceImpl
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author Ran_cc
 * @date 2018年8月10日
 * @版本 V 1.0
 */
@Service
public class ExcelServiceImpl implements ExcelService {

	@Resource
	private CrShopGoodsMapper goMapper;

	@Resource
	private CrShopGoodsSpecMapper specMapper;

	@Resource
	private CrShopGoodsTypeMapper goTypeMapper;
	@Resource
	private crShopPicMapper picMapper;
	@Resource
	private crShopPicTypeMapper pictMapper;

	private static final Logger log = LoggerFactory.getLogger(ExcelServiceImpl.class);

	/**
	 * <p>
	 * Title: readExcelFile
	 * </p>
	 * <p>
	 * Description:(一句话阐述):
	 * </p>
	 * 
	 * @param file
	 * @return
	 * @author Ran_cc
	 * @date 2018年8月10日
	 */
	@Override
	public String readExcelFile(MultipartFile file) {

		return ",";
	}

	/**
	 * <p>
	 * Title: readPinTuanExcelFile
	 * </p>
	 * <p>
	 * Description:(一句话阐述):
	 * </p>
	 * 
	 * @param file
	 * @return
	 * @author Ran_cc
	 * @date 2018年8月13日
	 */
	@Override
	public String readPinTuanExcelFile(MultipartFile file) {

		return ",";
	}

	/**
	 * <p>
	 * Title: readGoodsFile
	 * </p>
	 * <p>
	 * Description:(一句话阐述):
	 * </p>
	 * 
	 * @param file
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月28日
	 */
	@Transactional(rollbackFor = { Exception.class } , propagation = Propagation.REQUIRED)
	@Override
	public String readGoodsFile(MultipartFile file , String shopId) throws Exception {
		DecimalFormat df = new DecimalFormat("#");
		Map<String , String> ttMap = new HashMap<String , String>();
		int row = 0;
		String result = "";
		String d1 = StringUtil.DateToString(new Date() , 4);
		//		try {

		//查询出来所有的分类
		CrShopGoodsType tt = new CrShopGoodsType();
		tt.setShopId(shopId);
		tt.setStatus(1);
		List<CrShopGoodsType> goType = goTypeMapper.selectListBySelective(tt);
		for (int i = 0; i < goType.size(); i++) {
			ttMap.put(goType.get(i).getTitle() , goType.get(i).getId());
		}

		//查询出图片库默认相册信息
		crShopPicType pict = new crShopPicType();
		pict.setShopId(shopId);
		pict.setIsDefault(1);
		List<crShopPicType> pictList = pictMapper.selectListBySelective(pict);
		String picTypeId = "";
		if (pictList.size() > 0) {
			picTypeId = pictList.get(0).getId();
		}

		//创建处理EXCEL的类  
		ReadExcel readExcel = new ReadExcel();
		//解析excel，获取上传的事件单  
		List<Map<String , Object>> vipList = readExcel.getExcelInfo(file);
		//至此已经将excel中的数据转换到list里面了,接下来就可以操作list,可以进行保存到数据库,或者其他操作,  
		log.info("开始导入数据:共有 {}" , vipList.size());
		//		for (Map<String , Object> user : vipList) {
		JSONArray arr = new JSONArray();
		List<CrShopGoods> list = new ArrayList<CrShopGoods>();
		CrShopGoods go = null;
		Map<String , Object> user = null;
		List<CrShopGoodsSpec> spcList = null;
		List<crShopPic> picList = new ArrayList<crShopPic>();
		crShopPic piccc = null;
		CrShopGoodsSpec spec = null;
		for (int i = 0; i < vipList.size(); i++) {
			user = vipList.get(i);
			if (StringUtil.isEmpty(user.get("data1"))) {
				continue;
			}
			String dd1 = user.get("data1").toString();
			String d2 = user.get("data2") != null ? user.get("data2").toString() : "";
			String d3 = user.get("data3") != null ? user.get("data3").toString() : "";
			String d4 = user.get("data4").toString();
			String d5 = user.get("data5").toString();
			String d6 = user.get("data6").toString();
			String d7 = user.get("data7").toString();
			String d8 = user.get("data8").toString();
			String d9 = user.get("data9").toString();
			String d10 = user.get("data10").toString();
			String d11 = user.get("data11").toString();
			String d12 = user.get("data12") != null ? user.get("data12").toString() : "0";
			String d13 = user.get("data13") != null ? user.get("data13").toString() : "0";
			String d14 = user.get("data14").toString();
			String d15 = user.get("data15").toString();
			String d16 = user.get("data16") != null ? user.get("data16").toString() : "默认";//规格名称
			System.out.println("执行第{" + (i + 1) + "}条数据,商品标题:" + dd1);
			//			try {
			go = new CrShopGoods();

			go.setShopId(shopId);

			go.setGoodsTitle(dd1);
			String upload = "";
			File tempFile = null;
			String fileName = "";
			if ((d2.indexOf("https:") >= 0 || d2.indexOf("http:") >= 0) && d2.indexOf("chengpao8.cn") >= 0) {
				go.setGoodsPic(d2);
				/*
				 * piccc = new crShopPic();
				 * piccc.setPicTypeId(picTypeId);
				 * piccc.setTitle(StringUtil.getPastDate(0));
				 * piccc.setStatus(1);
				 * piccc.setPic(d2);
				 * piccc.setPicSize(CityUploadUtils.getImgWH(d2.toString()));
				 * picList.add(piccc);
				 */
			} else {
				go.setGoodsPic("http://cpimg.chengpao8.cn/dfghjklscvbndfghj.jpg");

				/*
				 * piccc = new crShopPic();
				 * piccc.setPicTypeId(picTypeId);
				 * tempFile = new File(d2.trim());
				 * fileName = tempFile.getName();
				 * piccc.setTitle(fileName.split("\\.")[0]);
				 * piccc.setStatus(1);
				 * upload = QNFileUpload.upload(d2 , StringUtil.getUUID() + fileName);
				 * upload = QNFileUpload.QINIUPATH + upload;
				 * piccc.setPic(upload.toString());
				 * piccc.setPicSize(CityUploadUtils.getImgWH(upload.toString()));
				 * picList.add(piccc);
				 * go.setGoodsPic(upload); //此处需要上传
				 */ }

			String[] picArr = d3.split("\\|");
			StringBuffer pciStr = new StringBuffer();
			for (int j = 0; j < picArr.length; j++) {
				if ((picArr[j].indexOf("https:") >= 0 || picArr[j].indexOf("http:") >= 0)
						&& picArr[j].indexOf("chengpao8.cn") >= 0) {
					pciStr.append(picArr[j]);
					/*
					 * piccc = new crShopPic();
					 * piccc.setPicTypeId(picTypeId);
					 * piccc.setTitle(StringUtil.getPastDate(0));
					 * piccc.setStatus(1);
					 * piccc.setPic(picArr[i]);
					 * piccc.setPicSize(CityUploadUtils.getImgWH(picArr[i].toString()));
					 * picList.add(piccc);
					 */
				} else {
					/*
					 * tempFile = new File(picArr[i].trim());
					 * fileName = tempFile.getName();
					 * upload = QNFileUpload.upload(picArr[i] , StringUtil.getUUID() + fileName);
					 * upload = QNFileUpload.QINIUPATH + upload;
					 * piccc = new crShopPic();
					 * piccc.setPicTypeId(picTypeId);
					 * piccc.setTitle(fileName.split("\\.")[0]);
					 * piccc.setStatus(1);
					 * piccc.setPic(upload.toString());
					 * piccc.setPicSize(CityUploadUtils.getImgWH(upload.toString()));
					 * picList.add(piccc);
					 * pciStr.append(upload);
					 */
				}
				if ((j + 1) < picArr.length) {
					pciStr.append(",");
				}
			}
			go.setGoodsPicArr(pciStr.toString());//此处需要上传
			go.setGoodsSupport(d4.equals("3") ? "1,2" : d4);
			go.setPriceOut(Integer.parseInt(df.format((Double.parseDouble(d5.split("\\|")[0]) * 100))));
			go.setPriceRoom(Integer.parseInt(df.format((Double.parseDouble(d6.split("\\|")[0]) * 100))));
			go.setGoodsStock(Integer.parseInt(d7.split("\\|")[0]));
			go.setGoodsPackAmount(Integer.parseInt(df.format((Double.parseDouble(d8.split("\\|")[0]) * 100))));
			go.setStatus(Integer.parseInt(d9));
			//分类
			if (StringUtil.isEmpty(ttMap.get(d10))) {
				//如果没有当前分类, 则,全部回滚, 并提示消息
				throw new Exception("导入失败，商品分类[" + d10 + "]没有被创建，请核对后重新导入");
			}
			go.setGoodsTypeId(ttMap.get(d10));

			go.setSort(Integer.parseInt(d11));
			go.setGoodsLimitBuy(Integer.parseInt(StringUtil.isNotBlank(d12) ? d12 : "0"));
			go.setGoodsStartAt(Integer.parseInt(StringUtil.isNotBlank(d13) ? d13 : "0"));
			go.setGoodsTitleSimple(d14);
			go.setGoodsDetail(d15);
			//处理规格
			String[] sp = d16.split("\\|");
			//								if (sp.length > 0) {
			spcList = new ArrayList<CrShopGoodsSpec>();
			for (int j = 0; j < sp.length; j++) {

				spec = new CrShopGoodsSpec();
				spec.setPriceOut(Integer.parseInt(df.format((Double.parseDouble(d5.split("\\|")[j]) * 100))));
				spec.setPriceRoom(Integer.parseInt(df.format((Double.parseDouble(d6.split("\\|")[j]) * 100))));
				spec.setGoodsStock(Integer.parseInt(d7.split("\\|")[j]));
				spec.setGoodsPackAmount(Integer.parseInt(df.format((Double.parseDouble(d8.split("\\|")[j]) * 100))));
				spec.setStatus(1);
				spec.setTitle(sp[j]);
				spcList.add(spec);
			}
			go.setSpecList(spcList);
			list.add(go);
			//					}
			row++;
			//			} catch (Exception e) {
			//				MyException.writeErr(e , "");
			//			}
		}

		//导入菜品
		goMapper.insertBatch(list);
		spcList = new ArrayList<CrShopGoodsSpec>();
		for (int j = 0; j < list.size(); j++) {
			spec = new CrShopGoodsSpec();
			CrShopGoods goods = list.get(j);
			List<CrShopGoodsSpec> list2 = goods.getSpecList();
			for (int k = 0; k < list2.size(); k++) {
				CrShopGoodsSpec goodsSpec = list2.get(k);
				goodsSpec.setGoodsId(IdTypeHandler.encode(Long.parseLong(goods.getId())));
				spcList.add(goodsSpec);
			}
		}
		//导入菜品规格
		specMapper.insertBatch(spcList);

		//导入图片库
		//picMapper.insertBatch(picList);
		System.out.println("done!");
		//		} catch (Exception e) {
		//			MyException.writeErr(e , "上传失败...");
		//			return "error";
		//		}
		String d2 = StringUtil.DateToString(new Date() , 4);
		log.info("导入完成  新增:{}条,执行共用时:{}" , row , StringUtil.getDistanceTime(d1 , d2));
		result = "success";
		return result;
	}

	public static void main(String[] args) {
		DecimalFormat df = new DecimalFormat("#");
		String s = "4";
		int i = Integer.parseInt(df.format((Double.parseDouble(s) * 100)));
		System.out.println(i);
	}

	/**
	 * <p>
	 * Title: readGoodsTypeFile
	 * </p>
	 * <p>
	 * Description:(一句话阐述):
	 * </p>
	 * 
	 * @param file
	 * @param shopId
	 * @return
	 * @author Ran_cc
	 * @date 2019年3月19日
	 */
	@Transactional(rollbackFor = { Exception.class } , propagation = Propagation.REQUIRED)
	@Override
	public String readGoodsTypeFile(MultipartFile file , String shopId) throws Exception {
		DecimalFormat df = new DecimalFormat("#");
		Map<String , String> ttMap = new HashMap<String , String>();
		int row = 0;
		String result = "";
		String d1 = StringUtil.DateToString(new Date() , 4);
		//		try {

		//查询出来所有的分类
		/*
		 * CrShopGoodsType tt = new CrShopGoodsType();
		 * tt.setShopId(shopId);
		 * tt.setStatus(1);
		 * List<CrShopGoodsType> goType = goTypeMapper.selectListBySelective(tt);
		 * for (int i = 0; i < goType.size(); i++) {
		 * ttMap.put(goType.get(i).getTitle() , goType.get(i).getId());
		 * }
		 */

		//创建处理EXCEL的类  
		ReadExcel readExcel = new ReadExcel();
		//解析excel，获取上传的事件单  
		List<Map<String , Object>> vipList = readExcel.getExcelInfo(file);
		//至此已经将excel中的数据转换到list里面了,接下来就可以操作list,可以进行保存到数据库,或者其他操作,  
		log.info("开始导入数据:共有 {}" , vipList.size());
		//		for (Map<String , Object> user : vipList) {
		JSONArray arr = new JSONArray();
		List<CrShopGoodsType> list = new ArrayList<CrShopGoodsType>();
		CrShopGoodsType go = null;
		Map<String , Object> user = null;
		for (int i = 0; i < vipList.size(); i++) {
			user = vipList.get(i);
			if (StringUtil.isEmpty(user.get("data1"))) {
				continue;
			}
			String dd1 = user.get("data1").toString();
			String d2 = user.get("data2") != null ? user.get("data2").toString() : "0";

			System.out.println("执行第{" + (i + 1) + "}条数据,商品标题:" + dd1);
			go = new CrShopGoodsType();
			go.setSort(Integer.parseInt(d2));
			go.setTitle(dd1);
			go.setShopId(shopId);
			list.add(go);
			row++;
		}
		//导入菜品类型
		goTypeMapper.insertBatch(list);
		System.out.println("done!");
		String d2 = StringUtil.DateToString(new Date() , 4);
		log.info("导入完成  新增:{}条,执行共用时:{}" , row , StringUtil.getDistanceTime(d1 , d2));
		result = "success";
		return result;
	}
}
